package com.cn.jdia.db.utils;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.cn.jdia.db.manager.DBManager4Mysql;
import com.cn.jdia.db.manager.DBManager4Oracle;

public class ConnectChecker {

	public static List<Map<String, String>> check(List<Map<String, String>> configList) {

		List<Map<String, String>> checkList = new ArrayList<>();

		try {
			for (Map<String, String> map : configList) {
				// System.out.println(map.get("servername") + " ");
				String url = null;
				int ret = -1;

				if (("MySql").equals(map.get("dbtype"))) {
					url = "jdbc:mysql://" + map.get("ip") + ":" + map.get("port") + "/";
					DBManager4Mysql db = DBManager4Mysql.createInstance();
					ret = db.connectDB(url, map.get("user"), map.get("pwd"));

					if (ret == 0) {
						int max = 0;
						int active = 0;

						ResultSet rs = db.executeQuery(ConstansUtils.MYSQL_MAX);
						while (rs.next()) {
							max = rs.getInt("Value");
						}
						rs.close();

						ResultSet rs2 = db.executeQuery(ConstansUtils.MYSQL_ACTIVE);
						while (rs2.next()) {
							active++;
						}
						rs2.close();

						map.put("max", max + "");
						map.put("active", active + "");
					}

					db.closeDB();
				} else if ("Oracle".equals(map.get("dbtype"))) {
					url = "jdbc:oracle:thin:@" + map.get("ip") + ":" + map.get("port") + "/" + map.get("sid");

					DBManager4Oracle db = DBManager4Oracle.createInstance();
					ret = db.connectDB(url, map.get("user"), map.get("pwd"));

					if (ret == 0) {
						int max = 0;
						int active = 0;

						ResultSet rs = db.executeQuery(ConstansUtils.ORACLE_MAX);
						while (rs.next()) {
							max = rs.getInt("VALUE");
						}
						rs.close();

						ResultSet rs2 = db.executeQuery(ConstansUtils.ORACLE_ACTIVE);
						while (rs2.next()) {
							active = rs2.getInt("LINES");
						}
						rs2.close();

						map.put("max", max + "");
						map.put("active", active + "");
					}

					db.closeDB();
				}

				// System.out.println(map.get("ip") + " TestRet: " + ret);
				if (ret == 0) {
					map.put("checked", "right");

				} else {
					map.put("checked", "wrong");
				}

				checkList.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return checkList;

	}
}
